package com.dsunsoft.rtu.web;

import com.dsunsoft.rtu.common.entity.RestCode;
import com.dsunsoft.rtu.common.entity.RestResult;
import com.dsunsoft.rtu.common.exception.BizException;
import com.dsunsoft.rtu.common.util.SecurityUtils;
import com.dsunsoft.rtu.core.base.BaseRestController;
import com.dsunsoft.rtu.dto.SysUserDto;
import com.dsunsoft.rtu.dto.SysUserMenuDto;
import com.dsunsoft.rtu.entity.SysUser;
import com.dsunsoft.rtu.query.SysUserQuery;
import com.dsunsoft.rtu.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/sysUser")
public class SysUserController extends BaseRestController<SysUser, SysUserQuery> {

    @Autowired
    private SysUserService sysUserService;

    @PostMapping("/getMenu")
    public RestResult<SysUserMenuDto> getMenu() {
        String userId = SecurityUtils.getCurrentUserLogin();
        if (StringUtils.isEmpty(userId)) {
            throw new BizException("未获取到用户信息,请重新登录");
        }
        SysUserMenuDto menuDto = sysUserService.getUserMenu(userId);
        return new RestResult<>(RestCode.SUCCESS, menuDto);
    }

    @PostMapping("/save")
    public RestResult<String> save(@RequestBody @Validated SysUserDto sysUser) {
        if (!sysUserService.checkLoginName(sysUser.getOldLoginName(), sysUser.getLoginName())) {
            return new RestResult<>(RestCode.USER_EXISTS, null, sysUser.getLoginName() + " 登录名已存在!");
        }
        sysUserService.save(sysUser);
        return new RestResult<>(RestCode.SUCCESS);
    }
}
